const { spawnSync } = require("child_process");

if ((process.env.NODE_OPTIONS || "").includes("--import tsx")) {
	require("typeorm/cli");
} else {
	let args = process.argv;
	const cmd = args[0]; // 执行的命令
	args = args.slice(1);
	let errmsg = "";
	if (args[1] === "generate") {
		if (args.length < 3 || args[2].startsWith("-")) {
			errmsg = "generate command need a migration name";
		} else {
			args[2] = `migrate/migrations/${args[2]}`;
			args.push("-p");
		}
	}
	if (!args[1].startsWith("migration:")) {
		args[1] = `migration:${args[1]}`;
	}

	if (errmsg) {
		console.error(errmsg);
		process.exit(1);
	} else {
		const argSet = new Set(args);
		if (argSet.has("help")) {
			argSet.delete("help");
			argSet.add("--help");
		}

		if (!argSet.has("-d")) {
			argSet.add("-d");
			argSet.add("migrate/data_source.js");
		}

		const childProcess = spawnSync(cmd, [...argSet], {
			stdio: "inherit",
			env: {
				...process.env,
				NODE_OPTIONS: [
					process.env.NODE_OPTIONS,
					"--import tsx",
					"--no-warnings",
				]
					.filter((item) => !!item)
					.join(" "),
			},
			windowsHide: true,
		});
		process.exit(childProcess.status || 0);
	}
}
